Responses and Failures
Let’s learn about responses that succeed and fail in clean architecture.
We'll cover the following
There’s a wide range of errors that can occur when the use case code is executed. We discussed validation errors in the previous lesson, “Request Validation”. There are many other errors that can also occur, such as business logic errors and errors from the repository layer or other external systems that the use case interfaces with. Regardless of what error occurs, the use case should always return an object with a known structure (the response). So, we need a new object that provides good support for different types of failures.
Update the test case for responses#
As with requests, there’s no unique way to provide such a response object. The following code is one of several possible solutions. In this solution, after making necessary imports, we test that responses have a boolean value.
Then we test the structure of responses, checking type and value. ResponseFailure objects should also have a message attribute, as follows:
The remaining tests are all about ResponseFailure. First, we test to check if ResponseFailure can be initialized with an exception, as in the following:
In order to be able to build a response directly from an invalid request and to get all the errors that the invalid request contains, we should run our tests as follows:
Update the responses#
Let’s write the classes that make the tests pass:
Through the _format_message() method, we enable the class to accept both string messages and Python exceptions. This is very handy when dealing with external libraries that can raise exceptions that we either don’t know or simply don’t want to manage.
The error types contained in the ResponseTypes class are very similar to HTTP errors. This similarity will be useful to us later when we return responses from the web framework. PARAMETERS_ERROR signals that something was wrong in the input parameters passed by the request.
RESOURCE_ERROR signals that the process ended correctly, but the requested resource isn’t available. Lastly, SYSTEM_ERROR signals that something went wrong with the process itself. These are used mostly to signal an exception in the Python code.
Updated code#
In the code editor, we’ve updated the files with the new code.
/
Request Validation
Error Management in a Use Case